package com.trust.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.trust.agri.exception.ServiceException;
import com.trust.agri.util.BeanUtil;
import com.trust.constant.Constants;
import com.trust.entity.DTO.PurchaseDTO;
import com.trust.entity.InventoryMaterial;
import com.trust.entity.InventoryRecord;
import com.trust.entity.Param.PurchaseListParam;
import com.trust.entity.Purchase;
import com.trust.entity.PurchaseDetail;
import com.trust.entity.VO.PurchaseVO;
import com.trust.mapper.PurchaseMapper;
import com.trust.service.*;
import com.trust.util.DateUtil;
import com.trust.util.NullCheck;
import com.trust.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Service
public class PurchaseServiceImpl extends ServiceImpl<PurchaseMapper, Purchase> implements PurchaseService {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private InventoryMaterialService inventoryMaterialService;

    @Resource
    private InventoryRecordService inventoryRecordService;

    @Resource
    private SystemPersonService systemPersonService;

    @Resource
    private PurchaseDetailService purchaseDetailService;

    @Override
    public String generalInCode(){
        String sort = "";
        try {
            sort = redisUtil.get(Constants.REDIS_SORT).toString();
            if (sort == "999"){
                redisUtil.set(Constants.REDIS_SORT, "1");
            } else {
                redisUtil.set(Constants.REDIS_SORT, String.valueOf((Integer.valueOf(sort) + 1)));
            }
        }catch (Exception e){
            log.error("获取序号失败：");
            e.printStackTrace();
            redisUtil.set(Constants.REDIS_SORT, "2");
            sort = "1";
        }
        String res = DateUtil.nowDate("yyMMdd") + StringUtils.leftPad(sort, 3, "0");

        List<InventoryMaterial> materials = inventoryMaterialService.getByInCode("R" + res);
        List<InventoryRecord> records = inventoryRecordService.getByCode("C" + res);
        if (CollectionUtil.isNotEmpty(materials) || CollectionUtil.isNotEmpty(records)){
            return generalInCode();
        }
        return res;
    }


    @Override
    public Page<PurchaseVO> list(PurchaseListParam param) {
        LambdaQueryWrapper<Purchase> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(param.getCode())){
            wrapper.like(Purchase::getCode, param.getCode());
        }
        if (null != param.getStartTime() && null != param.getEndTime()){
            wrapper.between(Purchase::getPurchaseTime, param.getStartTime(), param.getEndTime());
        }
        wrapper.orderByDesc(Purchase::getId);
        Page<Purchase> page = this.page(new Page<>(param.getPageNum(), param.getPageSize()), wrapper);
        Page<PurchaseVO> targetPage = BeanUtil.sourcePage2targetPage(page, PurchaseVO.class);
        for (PurchaseVO record : targetPage.getRecords()) {
            record.setPrincipalName(null == record.getPrincipal() ? null : systemPersonService.getNameById(record.getPrincipal()));
            record.setRecorderName(null == record.getRecorder() ? null : systemPersonService.getNameById(record.getRecorder()));
            List<PurchaseDetail> list = purchaseDetailService.getByPurchaseId(record.getId());
            record.setPurchaseTimeStr(record.getPurchaseTime());
            record.setDetails(list);
        }
        return targetPage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Purchase saveAndUpdate(PurchaseDTO param) {
        Purchase target = BeanUtil.source2target(param, new Purchase());
        if (null != param.getId()){
            Purchase byId = this.getById(param.getId());
            if (byId.getState() > 0){
                throw new ServiceException("已入库，不能更新");
            }
        } else {
            target.setState(0);
        }
        this.saveOrUpdate(target);
        if (null != param.getId()){
            LambdaQueryWrapper<PurchaseDetail> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(PurchaseDetail::getPurchaseId, param.getId());
            purchaseDetailService.remove(wrapper);
        }
        for (PurchaseDetail detail : param.getDetails()) {
            NullCheck.isValid(detail);
            detail.setPurchaseId(target.getId());
            purchaseDetailService.save(detail);
        }
        return target;
    }
}
